package com.xpqh.ksg.modular.colorchange.service;

import com.xpqh.ksg.common.persistence.dao.KsgCarColorChangeMapper;
import com.xpqh.ksg.common.persistence.dao.KsgOverseasCarColorMapper;
import com.xpqh.ksg.common.persistence.model.KsgCarColorChange;
import com.xpqh.ksg.common.persistence.model.KsgOverseasCarColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ColorChangeService {

    @Autowired
    private KsgOverseasCarColorMapper ksgOverseasCarColorMapper;

    @Autowired
    private KsgCarColorChangeMapper ksgCarColorChangeMapper;

    /**
     * 获取色卡列表
     * @param pageNo 页码
     * @return 色卡列表
     */
    public List<KsgOverseasCarColor> getColorList(Integer pageNo) {
        int pageSize = 20;
        int offset = (pageNo - 1) * pageSize;
        return ksgOverseasCarColorMapper.getColorList(offset, pageSize);
    }

    /**
     * 保存渲染信息
     * @param carImgUrl 车辆照片
     * @param colorCardId 色卡Id
     * @param userId 用户Id
     * @return 渲染记录
     */
    public KsgCarColorChange saveColorChange(String carImgUrl, Integer colorCardId, Integer userId) {
        // 根据色卡Id获取色卡信息
        KsgOverseasCarColor carColor = ksgOverseasCarColorMapper.selectById(colorCardId);
        
        // 创建渲染记录
        KsgCarColorChange colorChange = new KsgCarColorChange();
        colorChange.setUserId(userId);
        colorChange.setCarImgUrl(carImgUrl);
        colorChange.setColorCardId(colorCardId);
        if (carColor != null) {
            colorChange.setColorName(carColor.getName());
        }
        colorChange.setStatus(0); // 0-渲染中
        colorChange.setCreateDate(new Date());
        colorChange.setUpdateDate(new Date());
        
        // 保存到数据库
        ksgCarColorChangeMapper.insert(colorChange);
        
        // 调用AI接口进行渲染（空方法实现）
        callAiRenderingService(colorChange);
        
        return colorChange;
    }

    /**
     * 获取用户渲染历史列表
     * @param userId 用户Id
     * @param pageNo 页码
     * @return 渲染历史列表
     */
    public List<KsgCarColorChange> getUserColorChangeHistory(Integer userId, Integer pageNo) {
        int pageSize = 10;
        int offset = (pageNo - 1) * pageSize;
        return ksgCarColorChangeMapper.getUserColorChangeHistory(userId, offset, pageSize);
    }

    /**
     * 调用AI接口进行渲染（空方法实现）
     * @param colorChange 渲染记录
     */
    private void callAiRenderingService(KsgCarColorChange colorChange) {
        // TODO: 实现AI接口调用逻辑
        // 这里应该调用AI服务生成新的车辆照片
        // 然后更新渲染记录的状态和结果图片URL
        
        // 示例：异步调用AI接口
        // aiService.renderCarColor(colorChange.getId(), colorChange.getCarImgUrl(), colorChange.getColorCardId());
    }

} 